package com.fenghongzhang.day015;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView lv;

    private View inflate;
    //总数据源
    private List<Food.DataBean> list;
    private int index = 0;
    private MyAdapter myAdapter;
    private String path = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=";
    private int num = 1;
    private boolean isLast = false;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //1,控件
        lv = (ListView) findViewById(R.id.lv);
        list = new ArrayList<>();
        //2.数据源
//        List<String> list = new ArrayList<>();
//        for (int i = 0; i < 30; i++) {
//            list.add("第"+i+"个");
//        }
        //异步下载,用Gson解析
        new MyTask().execute(path + num);//2

        //3,适配器
        myAdapter = new MyAdapter(list, MainActivity.this);//1
        lv.setAdapter(myAdapter);
//        ImageView imageView = new ImageView(this);
//        imageView.setImageResource(R.mipmap.ic_launcher);
//        lv.addHeaderView(imageView);

        //分割线的颜色
        lv.setDivider(getDrawable(R.color.colorAccent));
        //分割线的高度
        lv.setDividerHeight(10);

        inflate = LayoutInflater.from(this).inflate(R.layout.foot_layout, null);
//        lv.addFooterView(inflate);


        //lv的点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            /**
             *
             * @param parent
             * @param view
             * @param position 数据源中的小标
             * @param id
             */
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title = list.get(position).getTitle();
                Toast.makeText(MainActivity.this, title, Toast.LENGTH_SHORT).show();
            }
        });
        //lv的长按事件
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(MainActivity.this, "哈哈", Toast.LENGTH_SHORT).show();
                index = position;
                ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);

                progressDialog.setTitle("删除");
                progressDialog.setMessage("是否删除?");

                progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                    }
                });
                progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        list.remove(index);
                        myAdapter.notifyDataSetChanged();
                    }
                });

                progressDialog.show();
                //截断
                return true;
            }
        });


        //滑动监听
        /**
         * 到最后一页就加载数据
         *
         */
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isLast && scrollState == SCROLL_STATE_IDLE) {
                    //就是到底了
                    lv.addFooterView(inflate);
                    num++;
                    new MyTask().execute(path + num);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //是否到底
                isLast = (firstVisibleItem + visibleItemCount == totalItemCount);
            }
        });

    }

    public void btn(View view) {
//        lv.setSelection(2);
//        lv.removeFooterView(inflate);
    }

    //2.準備數據源
    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            URL url = null;
            try {
                url = new URL(strings[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                if (connection.getResponseCode() == 200) {
                    InputStream inputStream = connection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        buffer.append(new String(bytes, 0, len));
                    }
                    return buffer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //Gson
            Gson gson = new Gson();
            Food food = gson.fromJson(s, Food.class);
            //給數據源複製
            //把每次查询都有加入到数据源中.

            List<Food.DataBean> data = food.getData();
            list.addAll(data);

            //移除尾布局
            lv.removeFooterView(inflate);

            myAdapter.notifyDataSetChanged();
        }
    }

}
